package com.koutao.mall.config;

import com.koutao.mall.common.BusinessException;
import com.koutao.mall.common.ResultCode;
import com.koutao.mall.common.ResultData;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Date:     2020/9/27 17:44
 * Description: TODO
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResultData<String> businessExceptionHand(BusinessException e){
        return new ResultData(e.getCode(), e.getMessage());
    }

    /**
     * 一般的参数绑定时候抛出的异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public ResultData handleBindException(BindException ex){
        List<String> defaultMsg = ex.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        return new ResultData(ResultCode.ERROR_SERVICE.getCode(),defaultMsg.get(0));
    }

    @ExceptionHandler(Exception.class)
    public ResultData<String> exceptionHand(Exception e){
        return new ResultData(ResultCode.ERROR_SERVICE.getCode(), ResultCode.ERROR_SERVICE.getMsg() + Optional.ofNullable(e.getMessage()).orElse(""));
    }

}
